<template>
  <div class="student-events">
    <h1>校园活动</h1>
    
    <div class="user-info">
      <p>欢迎，{{ userProfile.fullName }} (学生)</p>
      <router-link to="/student/dashboard">返回Dashboard</router-link>
    </div>

    <!-- 活动列表 -->
    <div class="events-list-section">
      <h2>可报名的活动</h2>
      <div v-if="loading" class="loading">加载中...</div>
      <div v-else-if="events.length === 0" class="no-events">暂无活动</div>
      <div v-else class="events-list">
        <div v-for="event in events" :key="event.id" class="event-card">
          <h3>{{ event.title }}</h3>
          <p class="event-description">{{ event.description }}</p>
          <div class="event-details">
            <p><strong>时间:</strong> {{ formatDateTime(event.startTime) }} - {{ formatDateTime(event.endTime) }}</p>
            <p><strong>地点:</strong> {{ event.location }}</p>
            <p><strong>发布时间:</strong> {{ formatDate(event.createdAt) }}</p>
          </div>
          <div class="event-actions">
            <button 
              @click="registerEvent(event.id)" 
              :disabled="isRegistered(event.id)"
              :class="{ 'registered-btn': isRegistered(event.id) }"
            >
              {{ isRegistered(event.id) ? '已报名' : '报名参加' }}
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 我的报名 -->
    <div class="my-registrations-section">
      <h2>我的报名</h2>
      <div v-if="myRegistrationsLoading" class="loading">加载中...</div>
      <div v-else-if="myRegistrations.length === 0" class="no-events">暂无报名记录</div>
      <div v-else class="registrations-list">
        <div v-for="registration in myRegistrations" :key="registration.id" class="registration-card">
          <h3>{{ getEventTitle(registration.eventId) }}</h3>
          <p><strong>报名时间:</strong> {{ formatDateTime(registration.registeredAt) }}</p>
          <button @click="cancelRegistration(registration.id)" class="cancel-btn">取消报名</button>
        </div>
      </div>
    </div>

    <!-- 错误提示 -->
    <div v-if="error" class="error-message">
      {{ error }}
    </div>

    <!-- 成功提示 -->
    <div v-if="success" class="success-message">
      {{ success }}
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';

export default {
  name: 'StudentEvents',
  setup() {
    // 用户信息
    const userProfile = ref({});
    
    // 活动列表
    const events = ref([]);
    const loading = ref(false);
    
    // 我的报名
    const myRegistrations = ref([]);
    const myRegistrationsLoading = ref(false);
    
    // 状态信息
    const error = ref('');
    const success = ref('');

    // 获取用户信息
    const loadUserProfile = async () => {
      try {
        const response = await fetch('/user/profile', {
          method: 'GET',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json'
          }
        });
        
        const result = await response.json();
        if (result.code === 1) {
          userProfile.value = result.data;
        } else {
          error.value = result.msg || '获取用户信息失败';
        }
      } catch (err) {
        error.value = '网络错误，请稍后重试';
      }
    };

    // 获取活动列表
    const loadEvents = async () => {
      loading.value = true;
      try {
        const response = await fetch('/student/events', {
          method: 'GET',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json'
          }
        });
        
        const result = await response.json();
        if (result.code === 1) {
          events.value = result.data || [];
        } else {
          error.value = result.msg || '获取活动列表失败';
        }
      } catch (err) {
        error.value = '网络错误，请稍后重试';
      } finally {
        loading.value = false;
      }
    };

    // 获取我的报名
    const loadMyRegistrations = async () => {
      myRegistrationsLoading.value = true;
      try {
        const response = await fetch('/student/my-registrations', {
          method: 'GET',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json'
          }
        });
        
        const result = await response.json();
        if (result.code === 1) {
          myRegistrations.value = result.data || [];
        } else {
          error.value = result.msg || '获取报名列表失败';
        }
      } catch (err) {
        error.value = '网络错误，请稍后重试';
      } finally {
        myRegistrationsLoading.value = false;
      }
    };

    // 报名活动
    const registerEvent = async (eventId) => {
      try {
        const response = await fetch('/student/events/register', {
          method: 'POST',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ eventId })
        });
        
        const result = await response.json();
        if (result.code === 1) {
          success.value = result.msg || '报名成功';
          // 重新加载我的报名
          await loadMyRegistrations();
        } else {
          error.value = result.msg || '报名失败';
        }
      } catch (err) {
        error.value = '网络错误，请稍后重试';
      }
    };

    // 取消报名
    const cancelRegistration = async (registrationId) => {
      if (!confirm('确定要取消报名吗？')) {
        return;
      }
      
      try {
        const response = await fetch('/student/events/cancel-registration', {
          method: 'POST',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ registrationId })
        });
        
        const result = await response.json();
        if (result.code === 1) {
          success.value = result.msg || '取消报名成功';
          // 重新加载我的报名
          await loadMyRegistrations();
        } else {
          error.value = result.msg || '取消报名失败';
        }
      } catch (err) {
        error.value = '网络错误，请稍后重试';
      }
    };

    // 检查是否已报名
    const isRegistered = (eventId) => {
      return myRegistrations.value.some(reg => reg.eventId === eventId);
    };

    // 获取活动标题
    const getEventTitle = (eventId) => {
      const event = events.value.find(e => e.id === eventId);
      return event ? event.title : '未知活动';
    };

    // 格式化日期时间
    const formatDateTime = (dateTime) => {
      if (!dateTime) return '';
      return new Date(dateTime).toLocaleString('zh-CN');
    };

    // 格式化日期
    const formatDate = (date) => {
      if (!date) return '';
      return new Date(date).toLocaleDateString('zh-CN');
    };

    // 初始化
    onMounted(async () => {
      await loadUserProfile();
      await loadEvents();
      await loadMyRegistrations();
    });

    return {
      userProfile,
      events,
      loading,
      myRegistrations,
      myRegistrationsLoading,
      error,
      success,
      registerEvent,
      cancelRegistration,
      isRegistered,
      getEventTitle,
      formatDateTime,
      formatDate
    };
  }
};
</script>

<style scoped>
.student-events {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

.user-info {
  background-color: #f5f5f5;
  padding: 15px;
  border-radius: 5px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.events-list-section, .my-registrations-section {
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 20px;
  margin-bottom: 20px;
}

.events-list-section h2, .my-registrations-section h2 {
  margin-top: 0;
}

.event-card, .registration-card {
  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 20px;
  margin-bottom: 20px;
}

.event-card h3, .registration-card h3 {
  margin-top: 0;
  color: #333;
}

.event-description {
  color: #666;
  margin-bottom: 15px;
}

.event-details p, .registration-card p {
  margin: 5px 0;
}

.event-actions {
  margin-top: 15px;
  display: flex;
  gap: 10px;
}

.registered-btn {
  background-color: #4CAF50 !important;
  color: white !important;
  cursor: not-allowed;
}

.registered-btn:hover {
  background-color: #4CAF50 !important;
}

.cancel-btn {
  background-color: #f44336;
  color: white;
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.cancel-btn:hover {
  background-color: #d32f2f;
}

.loading, .no-events {
  text-align: center;
  padding: 20px;
  color: #666;
}

.error-message {
  background-color: #f8d7da;
  color: #721c24;
  padding: 15px;
  border-radius: 5px;
  margin-bottom: 20px;
}

.success-message {
  background-color: #d4edda;
  color: #155724;
  padding: 15px;
  border-radius: 5px;
  margin-bottom: 20px;
}
</style>